package com.bdjk.bdmw.InfoGath.communication.server.tcp.netty;

import com.bdjk.bdmw.InfoGath.communication.dataProcess.DataProcess;
import com.bdjk.bdmw.InfoGath.communication.protocol.BaseProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;

public class CommThread
  implements Runnable
{
  private static final Logger logger = Logger.getLogger(CommThread.class);
  private String msg;
  private Channel channel;
  Map<String, Channel> map = new HashMap();
  
  public CommThread(String msg, Channel channel, Map<String, Channel> map)
  {
    this.msg = msg;
    this.channel = channel;
    this.map = map;
  }
  
  public void run()
  {
    DataProcess dataProcess = new DataProcess();
    dataProcess.messageHandle(this.msg);
    
    this.map.put(dataProcess.terIdent, this.channel);
    if ((dataProcess.protocol != null) && (dataProcess.isResponse))
    {
      logger.info("Response--------" + dataProcess.responseMsg + "---------");
      
      ByteBuf encoded = this.channel.alloc().buffer(4 * dataProcess.responseMsg.length());
      encoded.writeBytes(dataProcess.responseMsg.getBytes());
      this.channel.writeAndFlush(encoded).addListener(new ChannelFutureListener()
      {
        public void operationComplete(ChannelFuture future) throws Exception
        {
          if (!future.isSuccess()) {
            CommThread.logger.info("wrong");
          } else {
            CommThread.logger.info("success");
          }
        }
      });
      logger.info("Response--------" + dataProcess.responseMsg + "---------");
    }
    else
    {
      String msg = "no response";
      ByteBuf encoded = this.channel.alloc().buffer(4 * msg.length());
      encoded.writeBytes(msg.getBytes());
      
      this.channel.writeAndFlush(encoded).addListener(new ChannelFutureListener()
      {
        public void operationComplete(ChannelFuture future)
          throws Exception
        {
          if (!future.isSuccess()) {
            CommThread.logger.info("wrong");
          } else {
            CommThread.logger.info("success");
          }
        }
      });
    }
    try
    {
      Thread.sleep(5000);
      StringBuffer cmd = new StringBuffer();
      
      String command = dataProcess.protocol.off;
      //new Thread(new sendMessage(dataProcess.terIdent, command)).start();
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
  }
}
